package dse.messages.multiversion;

import java.util.LinkedList;

import dse.*;
import dse.messages.*;

public class RequestVersionTLOMessageHandler extends MessageSender implements
		MessageHandler {
	private DataObject dobj;
	private boolean ru;
	private VersionReader versionReader;
	private LinkedList<Node> rs;
	
	public RequestVersionTLOMessageHandler (
			Experiment experiment,
			DataObject dobj,
			boolean ru,
			LinkedList<Node> resvr,
			VersionReader versionReader
			)
	{
		super(experiment);
		
		this.dobj = dobj;
		this.ru = ru;
		this.rs = resvr;
		this.versionReader = versionReader;
	}
	
	@Override
	public boolean acceptMessage(Message message) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void messageInterupted(ExperimentRecorder recorder, Message message,
			double time) {
		// TODO Auto-generated method stub
		//recorder.debug(this, "msgIntrpt: " + message, time);
		versionReader.readVersion(recorder, -1, time);
	}

	@Override
	public void messageReceived(ExperimentRecorder recorder, Message message, double time) {
		// TODO Auto-generated method stub
		recorder.debug(this, "msgRcvd: " + message, time);
		if (message.messageType() != MessageType.RequestVersionTLO) {
			recorder.warn(
					"RequestVersionTLOMessageHandler recieved " + 
					message.messageType() + " message."
					);
			return;
		}
		Node sn = message.to();
		if(ru){
			Version max = sn.getMaxVersion(dobj, ru, 0);
			Message m = super.createVersionResponseV3Message(
				sn, message.from(), max.getSequence(), message.purpose(), versionReader);
			recorder.debug(this, "new msg: " + m, time);
			experiment.messageQueue().enqueueMessage(m, time);
		}
		else{
			Version max = sn.getMaxVersion(dobj, ru, dobj.shareCount()-experiment.modules().nodeEventScheduler().getEventsPerPeriod());
			sn.addCurReads(dobj, versionReader.getTransaction().id(), max);
			int count = dobj.requiredShareCount()+experiment.modules().nodeEventScheduler().getEventsPerPeriod();
			for(int i=0; i<count; i++){
				Message m = super.createRequestDesignatedShareTLOMessage(message.to(), rs.get(i), dobj, max, message.from(),
					MessagePurpose.DataObjectRequest, versionReader);
				recorder.debug(this, "new msg: " + m, time);
				experiment.messageQueue().enqueueMessage(m, time);
			}
		}
	}
}
